package com.hgs.iias.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UsernameNotFoundException;

import org.springframework.dao.DataAccessException;

import com.hgs.iias.domain.Role;
import com.hgs.iias.domain.User;
import com.hgs.iias.service.UserService;
import com.hgs.iias.service.exception.ObjectExistsException;

public class UserServiceImpl implements UserService, UserDetailsService {
	@PersistenceContext
	private EntityManager em;
	
	public List<User> list() {
		List<User> results = new ArrayList<User>();
		
		for(Object o: em.createQuery("SELECT u FROM User u").getResultList()) {
			results.add(User.class.cast(o));
		}
		
		return results;
	}
	
	public User load(String username) {
		return em.find(User.class, username);
	}
	
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
		User user = load(username);
		
		if(user == null) {
			throw new UsernameNotFoundException("User not found.");
		} else if(user.getAuthorities().length == 0) {
			throw new UsernameNotFoundException("User has no GrantedAuthority.");
		}
		
		return user;
	}
	
	public void modify(User user) {
		em.merge(user);
	}
	
	public void register(User user) {
		String username = user.getUsername();
		
		if(load(username) == null) {
			user.setEnabled(true);
			
			for(Object o: em.createQuery("SELECT r FROM Role r").getResultList()) {
				user.addRole(Role.class.cast(o));
			}
			
			em.persist(user);
		} else {
			throw new ObjectExistsException(username);
		}
	}
}
